﻿package com.image;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.util.DBConn;
import com.util.MyUtil;

public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private Connection conn = null;

	@Override
	public void init() throws ServletException {
		conn = DBConn.getConnection();
	}
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		process(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		process(request, response);
	}

	private void forward(HttpServletRequest request,
			HttpServletResponse response, String path) throws ServletException,
			IOException {
		RequestDispatcher rd = request.getRequestDispatcher(path);
		rd.forward(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String uri = request.getRequestURI();

		// //////////////////////////////////////////////////////
		if (uri.indexOf("list.do") != -1) {
			// 湲�由ъ뒪��
			MyUtil myUtil = new MyUtil();

			String pageNum = request.getParameter("pageNum");
			int current_page = 1;
			if (pageNum != null)
				current_page = Integer.parseInt(pageNum);

			int numPerPage = 9; // �쒗럹�댁����쒖떆��寃뚯떆臾���
			int total_page = 0;
			int total_dataCount = 0;
			String cp = request.getContextPath();

			ImageDAO dao = new ImageDAO(conn);

			List<ImageDTO> lists = null;
			try {
				total_dataCount = dao.getDataCount();

				if (total_dataCount != 0)
					total_page = myUtil.getPageCount(numPerPage,
							total_dataCount);

				if (current_page > total_page)
					current_page = total_page;

				int start = (current_page - 1) * numPerPage + 1;
				int end = current_page * numPerPage;

				lists = dao.getListData(start, end);

			} catch (Exception e) {
				// e.printStackTrace();
				System.out.println(e.toString());
			}

			String urlList = cp+ "/image/list.do";
			String imagePath =  cp+"/pds/saveFile";

			request.setAttribute("lists", lists);
			request.setAttribute("pageNum", new Integer(current_page));
			request.setAttribute("total_page", total_page);
			request.setAttribute("total_dataCount", total_dataCount);
			request.setAttribute("imagePath", imagePath);
			request.setAttribute("pageIndexList", myUtil.pageIndexList(current_page, total_page, urlList));

			forward(request, response, "/imageTest/list.jsp");
			return;

			// //////////////////////////////////////////////////////
		} else if (uri.indexOf("write.do") != -1) {
			// 湲��곌린��
			forward(request, response, "/imageTest/write.jsp");
			return;

			// //////////////////////////////////////////////////////
		} else if (uri.indexOf("write_ok.do") != -1) {
			// 湲��곌린 ��옣
			ImageDAO dao = new ImageDAO(conn);
			ImageDTO dto = new ImageDTO();
			try {
				String root = getServletContext().getRealPath("/");
				String path = root+"pds"+File.separator+"saveFile";
				
				// �낅줈�쒗븷 寃쎈줈媛�議댁옱�섏� �딆쑝硫�寃쎈줈 �묒꽦
				File dir = new File(path);
				if(!dir.exists())
					dir.mkdirs();
				
				String encType="utf-8";
				int maxFileSize = 5*1024*1024; // 理쒕� �ш린 : 5MB濡��ㅼ젙
				
				MultipartRequest multi = null;
				multi = new MultipartRequest(request, path, maxFileSize, encType, 
						new DefaultFileRenamePolicy());				
				
				int maxNum = dao.getMaxNum();
				
				dto.setNum(maxNum + 1);
				dto.setSubject(multi.getParameter("subject"));
				dto.setSaveFileName(multi.getFilesystemName("upload")); // �쒕쾭����옣���뚯씪紐�
				         // multi.getOriginalFileName("upload") : �ㅼ젣 �뚯씪紐�
				
				dao.insertData(dto);
			} catch (Exception e) {
				System.out.println(e.toString());
			}

			response.sendRedirect(request.getContextPath() + "/image/list.do");
			return;
			// //////////////////////////////////////////////////////
		} else if (uri.indexOf("delete.do") != -1) {

			int num = Integer.parseInt(request.getParameter("num"));

			ImageDAO dao = new ImageDAO(conn);
			try {
				// �ㅼ젣 �뚯씪 ��젣
				String root = getServletContext().getRealPath("/");
				String path = root+"pds"+File.separator+"saveFile";
				
				ImageDTO dto = dao.getReadData(num);
				
				String fullFileName = path+File.separator+dto.getSaveFileName();
				File dir = new File(fullFileName);
				if(dir.exists())
					dir.delete();
				
				// DB �뺣낫 ��젣
				dao.deleteData(num);
			} catch (Exception e) {
				System.out.println(e.toString());
			}

			response.sendRedirect(request.getContextPath() + "/image/list.do");
			return;
		}
	}

	@Override
	public void destroy() {
		DBConn.close();
	}
}